import axios from 'axios'
import { getToken } from '@ruifox-cms/utils/src/storage'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_SERVICE_BASE,
  // baseURL: 'http://10.10.0.78:9100',
  // baseURL: 'http://10.10.0.78:9113',
  timeout: 15000,
  headers: {
    'userid':1,
    'Content-Type': 'application/json;charset=utf-8',
    'X-token': getToken()
  }
})

// 请求拦截
service.interceptors.request.use(
  config => {
    config.headers['X-Timestamp'] = Date.now()
    return config
  },
  error => {
    if (process.env.NODE_ENV === 'development') console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data

    // 成功状态码
    if (res.code === 20000) {
      return res
    }

    // 失败状态码
    if (res.code === 50000) {
      ElMessage.error(res.message || '请求失败')
    }

    return Promise.reject(new Error(res.message || '请求失败'))
  },
  (error) => {
    console.error('Response error:', error)
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service
